<template>
  <div class="container" style="height: 100%">
    <div class="header"
         style="width: 100%;max-height: 7%;  border-bottom:1px solid rgba(0,0,0,0.1);background: #021625;border-bottom:0.5px solid #032982">
      <div class="return" @click="$router.push({name:'Market',params:{index:3}})"
           style="position: absolute;top:.6rem;left:1rem;width: 1.4rem;height: 1.4rem;z-index:999">
        <img src="static/img/return2.png" width="100%" height="100%"/>
      </div>
      <h2
        style="margin:0rem;height:2.5rem;padding-top:.3rem;font-size: 1.4rem;text-align: center;color:#ffffff">
        {{name}}
      </h2>
    </div>

    <div style="width: 100%;background:#141B21 " class="infoBox">
      <div style="width: 38%">
        <div style="color:#349C01">¥ {{currentPrice}}</div>
        <div style="color:green">≈${{currentUsd}}
          <span v-if="gains>0" style="color:green">+{{gains}}%</span>
          <span v-else-if="gains<0" style="color:red">{{gains}}%</span>
        </div>
      </div>
      <div style="width: 27%">
        <div style="color:#ebebeb">最高: <span style="color:green">{{max}}</span></div>
        <div style="color:#ebebeb">最低: <span style="color:red">{{min}}</span></div>
      </div>
      <div style="width: 35%">
        <div style="color:#ebebeb">24h涨幅 : <span v-if="percentChange24h>0" style="color:green">{{percentChange24h}}%</span>
          <span v-if="percentChange24h<0" style="color:red">{{percentChange24h}}%</span>
        </div>
        <div style="color:#ebebeb">24h成交 : <span style="color:red">{{volume24hCNY}}</span></div>
      </div>
    </div>

    <div class="chartBox">
      <div style="background: #141B21;color:#fff">
        <div @click="changeDataType(1)"><span :class="{active:dataType==1}">6h</span></div>
        <div @click="changeDataType(2)"><span :class="{active:dataType==2}">24h</span></div>
        <div @click="changeDataType(3)"><span :class="{active:dataType==3}">近7天</span></div>
        <div @click="changeDataType(4)"><span :class="{active:dataType==4}">近30天</span></div>
      </div>
      <div id="chartDiv"></div>
    </div>

    <div style="height: 20%;width: 100%;background: #141B21;" class="coinInfo">
      <div>
        <div>市值排名</div>
        <div>第<span style="color:#349C01"> {{rank}} </span>名</div>
      </div>
      <div>
        <div>流通市值</div>
        <div style="color:#349C01">¥ {{marketCap}}</div>
      </div>
      <div>
        <div>流通总量</div>
        <div style="color:#349C01">{{totalSupply}}</div>
      </div>
      <div>
        <div>发行总量</div>
        <div style="color:#349C01">{{maxSupply?maxSupply:totalSupply}}</div>
      </div>
    </div>
  </div>
</template>

<script>

  import {mapGetters, mapActions} from 'vuex'


  import axios from 'axios'

  export default {
    components: {},
    props: [],
    data() {
      return {
        name: this.$route.params.name,
        dataType: 1,
        rate: this.global.rate,
        rank: '',
        totalSupply: '',
        maxSupply: '',
        marketCap: '',
        currentPrice: '',
        currentUsd: '',
        percentChange24h: '',
        volume24h: '',
        volume24hCNY: '',
        gains: '',
        min: '',
        max: '',
        myChart:'',
        axis:[],
        axisData1:[],
        axisData2:[],
        axisData3:[],
        axisData4:[],
      }

    },
    computed: {
      ...mapGetters(['marketList'])
    },
    methods: {
      ...mapActions(['setMarketByIndex']),
      changeDataType(index) {
        this.dataType = index

        this.drawLine()
      },
      getAxis(dateType) {
        if(dateType==1&&this.axisData1.length>0)return this.axisData1
        if(dateType==2&&this.axisData2.length>0)return this.axisData2
        if(dateType==3&&this.axisData3.length>0)return this.axisData3
        if(dateType==4&&this.axisData4.length>0)return this.axisData4

        Date.prototype.format = function() {
            var s = '';
            var year=this.getFullYear();
            var mouth = (this.getMonth() + 1)>=10?(this.getMonth() + 1):('0'+(this.getMonth() + 1));
            var day = this.getDate()>=10?this.getDate():('0'+this.getDate());
            var hour=this.getHours()>=10?this.getHours():'0'+this.getHours();
            var min=this.getMinutes()>=10?this.getMinutes():'0'+this.getMinutes();
            s +=year+"-"+mouth + "-"+day+" "+hour+":"+min+":"+"00";
            return (s); // 返回日期。
        };
        Date.prototype.FormatD = function (fmt) { //author: meizz
          var o = {
            "M+": this.getMonth() + 1, //月份
            "d+": this.getDate(), //日
            "h+": this.getHours(), //小时
            "m+": this.getMinutes(), //分
            "s+": this.getSeconds(), //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds() //毫秒
          };
          if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
          for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
          return fmt;
        }

        let begin;
        let end;
        let date=new Date();
        end = date.FormatD("yyyy-MM-dd hh:mm:ss");
        end=end.substring(0,14)+(parseInt(end.substring(14,16))-parseInt(end.substring(14,16))%5)+end.substring(16,end.length);

        if(dateType==1){
          date.setTime(date.getTime()-1000*60*60*6)
          begin = date.FormatD("yyyy-MM-dd hh:mm:ss")
          begin=begin.substring(0,14)+(parseInt(begin.substring(14,16))-parseInt(begin.substring(14,16))%5)+begin.substring(16,begin.length);
        }else if(dateType==2){
          date.setTime(date.getTime()-1000*60*60*24)
          begin = date.FormatD("yyyy-MM-dd hh:mm:ss")
          begin=begin.substring(0,14)+(parseInt(begin.substring(14,16))-parseInt(begin.substring(14,16))%5)+begin.substring(16,begin.length);
        }else if(dateType==3){
          date.setTime(date.getTime()-1000*60*60*24*7)
          begin = date.FormatD("yyyy-MM-dd hh:mm:ss")
          begin=begin.substring(0,14)+(parseInt(begin.substring(14,16))-parseInt(begin.substring(14,16))%5)+begin.substring(16,begin.length);
        }else if(dateType==4){
          date.setTime(date.getTime()-1000*60*60*24*30)
          begin = date.FormatD("yyyy-MM-dd hh:mm:ss")
          begin=begin.substring(0,14)+(parseInt(begin.substring(14,16))-parseInt(begin.substring(14,16))%5)+begin.substring(16,begin.length);
        }


        var ab = begin.split("-");
        var am=begin.split(":");
        var ae = end.split("-");
        var am2=end.split(":");
        var db = new Date();
        db.setUTCFullYear(ab[0], ab[1] - 1, ab[2].substring(0,2));
        db.setHours(am[0].substring(11,13))
        db.setMinutes(am[1]);
        db.setSeconds(0);
        var de = new Date();
        de.setUTCFullYear(ae[0], ae[1] - 1, ae[2].substring(0,2));
        de.setHours(am2[0].substring(11,13))
        de.setMinutes(am2[1]);
        de.setSeconds(0);
        var unixDb = db.getTime();
        var unixDe = de.getTime();


        this.axis=[]
        let i=0
        for (var k = unixDb;k <= unixDe;) {
          if(i>0){
            this.axis.push((new Date(parseInt(k))).format())
          }
          i++
          k = k + 1000*60*5;
        }


        for(let i=0;i<this.axis.length;i++){
          if(dateType==1){
            this.axisData1.push(this.axis[i])
          }else if(dateType==2){
            this.axisData2.push(this.axis[i])
          }else if(dateType==3){
            this.axisData3.push(this.axis[i])
          }else if(dateType==4){
            this.axisData4.push(this.axis[i])
          }
        }

        if(dateType==1){
          return this.axisData1
        }else if(dateType==2){
          return this.axisData2
        }else if(dateType==3){
          return this.axisData3
        }else if(dateType==4){
          return this.axisData4
        }

      },

      convertCurrency(money) {
        if (money > 100000000) {
          return parseFloat((money / 100000000).toFixed(2)) + '亿'
        } else if (money < 100000000 && money > 10000) {
          return parseFloat((money / 10000).toFixed(2)) + '万'
        } else {
          return money
        }
      },
      getTrendNew(){
        let _this=this;
        axios.get(_this.global.apiPath+'/ticker/getNowTicker?symbol=' + this.name).then((resp) => {
console.log(resp)
          // _this.min = parseFloat(resp.data.data.min.toFixed(4))
          // _this.max = parseFloat(resp.data.data.max.toFixed(4))

          let obj=resp.data.data
          _this.currentUsd = parseFloat(parseFloat(obj.priceUsd).toFixed(2))
          _this.currentPrice = parseFloat(parseFloat(obj.priceUsd * _this.rate).toFixed(2))
          _this.gains = parseFloat(parseFloat(obj.percentChange24h).toFixed(2))
          _this.percentChange24h = parseFloat(obj.percentChange24h)
          _this.volume24h = parseFloat(obj.volume24h)
          _this.volume24hCNY = _this.convertCurrency(obj.volume24hUsd * _this.rate)
          _this.rank = obj.rank
          //_this.totalSupply = _this.convertCurrency(obj.totalSupply)
          _this.totalSupply = _this.convertCurrency(obj.availableSupply)

          _this.maxSupply = _this.convertCurrency(obj.maxSupply)
          _this.marketCap = _this.convertCurrency(obj.marketCapUsd)
        })
      },
      drawLine() {

        let _this = this;
        _this.myChart.showLoading({
          text: 'loading',
          color: '#128CFB',
          textColor: '#fff',
          maskColor: 'rgba(255, 255, 255, 0)',
          zlevel: 0
        })
        _this.myChart.clear()
       let axisArr=_this.getAxis(_this.dataType);
      let fullAxis=[];
        for(let i=0;i<axisArr.length;i++){
          if(_this.dataType==1||_this.dataType==2){
            fullAxis.push(axisArr[i].substring(11,16))
          }else if(_this.dataType==3||_this.dataType==4){
            fullAxis.push(axisArr[i].substring(5,7)+"-"+axisArr[i].substring(8,10)+' '+axisArr[i].substring(11,16))
          }
        }



        let seriesData = []
        axios.get(_this.global.apiPath+'/ticker/getTickerData?symbol=' + this.name + '&dateType=' + this.dataType).then((resp) => {
console.log(resp)
          if (resp.status == 200) {
            let min = resp.data.data.min;
            let max = resp.data.data.max;
            let datas=resp.data.data.datas

            _this.min = parseFloat(min.toFixed(2))
            _this.max =  parseFloat(max.toFixed(2))

            if(datas.length<axisArr.length){
              let none=axisArr.length-datas.length
              for(let i=0;i<axisArr.length;i++){
                if(i<none){
                  seriesData.push('')
                }
              }
              seriesData=seriesData.concat(datas);
            }else{
              seriesData=datas
            }

            for(let i=0;i<seriesData.length;i++){
              if(seriesData[i])seriesData[i]=parseFloat(seriesData[i]).toFixed(2)
            }


            let option = {
              backgroundColor: '#141B21',
              // title: {
              //   text: parseFloat((this.currentAccount.ethBalance/Math.pow(10,18)).toFixed(6)),
              //   subText: '≈￥2456',
              //   textStyle: {fontWeight: 'normal', fontSize: 18},
              //   left: 'center',
              //   top: '1'
              // },
              tooltip: {
                trigger: 'axis', axisPointer: {
                  lineStyle: {color: '#57617B'},
                },
                // formatter: function (value, index) {
                //   console.log(value,index)
                //   if(_this.dataType==1||_this.dataType==2){
                //     return value.substring(11,16)
                //   }else if(_this.dataType==3||_this.dataType==4){
                //     return value.substring(5,7)+"/"+value.substring(8,10)
                //   }
                // }
              },
              legend: {icon: 'circle', data: ['数量', '资产(¥)'], right: '1%'},
              grid: {left: '5%', right: '8%', bottom: '0%', top: '12%', containLabel: true},
              xAxis: [{
                type: 'category',
                boundaryGap: true,
                axisLabel: {textStyle: {fontSize: 12, color: '#bfc5ca'}},
                axisLine: {lineStyle: {color: '#57617B'}},
                splitLine: {show: false},
                axisTick: {show: false},
                data: fullAxis,
                // axisLabel: {
                //   formatter:function(value,index){
                //   console.log(value)
                //
                //     if(_this.dataType==1||_this.dataType==2){
                //       return value.substring(11,16)
                //     }else if(_this.dataType==3||_this.dataType==4){
                //      return value.substring(5,7)+"/"+value.substring(8,10)
                //     }
                //   }
                // },
              }],
              yAxis: [{
                type: 'value', /* interval: 20,*/

                position: 'left',
                boundaryGap: true,
                axisTick: {show: false},
                // min:parseInt(min*0.9)-parseInt(min*0.9)%100,

                min: (min*0.9).toFixed(0)>min?((min-1)*0.9).toFixed(0):(min*0.9).toFixed(0),
                // max:max>1?(max+(max-min)).toFixed(0):'auto',
                axisLine: {lineStyle: {color: '#57617B'}},
                splitLine: {show: true},
                axisLabel: {
                  textStyle: {fontSize: 12, color: '#bfc5ca'},
                  // formatter: function (value) {
                  //   return value.toFixed(2)
                  // }
                }
              }],
              series: [{
                type: 'line',
                smooth: true, /* label:{ normal:{ show:true } },*/
                lineStyle: {normal: {width: 1, color: '#1C93FF'}},
                areaStyle: {
                  normal: {
                    color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                      offset: 0,
                      color: 'rgba(82, 191, 255, 1)'
                    }, {
                      offset: 0.8,
                      color: 'rgba(82, 191, 255, 0.5)'
                    }], false),
                    shadowColor: 'rgba(228, 139, 76, 0.5)',
                    shadowBlur: 10
                  }
                },
                markPoint: {

                  data: [
                    {type: 'max', name: '最大值', itemStyle: {color: '#08A32A'}},
                    {type: 'min', name: '最小值', itemStyle: {color: '#EC2D2D'}}
                  ],
                  symbolSize: 50,
                  animationDelay: 600,
                  animationDuration: 600
                },
                data: seriesData
              }]
            };
            _this.myChart.hideLoading()
            _this.myChart.setOption(option);
          }
        })
      }
    },
    watch: {},
    async mounted() {

      this.getTrendNew(this.name)
      this.myChart=this.$echarts.init(document.getElementById('chartDiv'))
      this.drawLine()
    }
  }
</script>
<style scoped>
  @import url("../../assets/css/marketinfo.css");
</style>

